import { useTranslation } from 'react-i18next';
import { motion, AnimatePresence } from 'framer-motion';
import { useState } from 'react';

export function LanguageSwitcher() {
  const { i18n } = useTranslation();
  const [isOpen, setIsOpen] = useState(false);

  const changeLanguage = (lng: string) => {
    i18n.changeLanguage(lng);
    localStorage.setItem('language', lng);
    setIsOpen(false);
  };

  return (
  <div 
    className="relative inline-block w-full md:w-auto"
    onMouseEnter={() => window.innerWidth >= 768 && setIsOpen(true)}
    onMouseLeave={() => window.innerWidth >= 768 && setIsOpen(false)}
  >
    <button 
      className="flex items-center flex-nowrap text-nowrap justify-between w-full appearance-none bg-transparent text-gray-700 py-2 px-4 pr-8 rounded-lg focus:outline-none text-sm font-medium hover:text-blue-500 transition-colors duration-300"
      onClick={() => window.innerWidth < 768 && setIsOpen(!isOpen)}
    >
      {i18n.language === 'ja' ? '日本語' : '中文'}
      <i className={`fa-solid fa-chevron-down ml-2 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`}></i>
    </button>
      
      <AnimatePresence>
        
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="absolute left-0 mt-2 w-full md:w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50"
          >
            <div 
              className="px-4 py-2 hover:bg-gray-100 cursor-pointer transition-colors"
              onClick={() => changeLanguage('ja')}
            >
              日本語 
              {i18n.language === 'ja' && <i className="fa-solid fa-check ml-2 text-blue-500"></i>}
            </div>
            <div 
              className="px-4 py-2 hover:bg-gray-100 cursor-pointer transition-colors"
              onClick={() => changeLanguage('zh')}
            >
              中文
              {i18n.language === 'zh' && <i className="fa-solid fa-check ml-2 text-blue-500"></i>}
            </div>
            
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}